/**
 * 上传服务 - 封装阿里云OSS上传相关API
 */

// 导入配置文件
import config from '@/config/app.js'

// 后端API基础URL
const BASE_URL = config.AI_HTTP_REQUEST_URL;

/**
 * 上传图片到阿里云OSS
 * @param {string} filePath - 本地文件路径
 * @param {Object} options - 可选配置
 * @returns {Promise<Object>} 上传结果
 */
export const uploadImageToOss = async (filePath, options = {}) => {
  return new Promise((resolve, reject) => {
    try {
      // 显示上传进度
      uni.showLoading({
        title: '上传中...',
        mask: true
      });

      // 创建上传任务
      const uploadTask = uni.uploadFile({
        url: `${BASE_URL}/upload/oss/image`,
        filePath: filePath,
        name: 'file',
        header: {
          'Content-Type': 'multipart/form-data'
        },
        success: (res) => {
          uni.hideLoading();
          
          if (res.statusCode === 200) {
            try {
              const result = JSON.parse(res.data);
              
              if (result.code === 200) {
                // 上传成功
                uni.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 2000
                });
                
                resolve({
                  success: true,
                  data: result.data,
                  message: result.message
                });
              } else {
                // 业务错误
                const error = new Error(result.message || '上传失败');
                console.error('上传失败:', error);
                
                uni.showToast({
                  title: error.message || '上传失败',
                  icon: 'error',
                  duration: 3000
                });
                
                resolve({
                  success: false,
                  error: error.message
                });
              }
            } catch (parseError) {
              console.error('解析响应失败:', parseError);
              resolve({
                success: false,
                error: '响应格式错误'
              });
            }
          } else {
            // HTTP错误
            const error = new Error(`HTTP错误: ${res.statusCode}`);
            console.error('上传失败:', error);
            
            uni.showToast({
              title: error.message || '上传失败',
              icon: 'error',
              duration: 3000
            });
            
            resolve({
              success: false,
              error: error.message
            });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          const error = new Error(`网络错误: ${err.errMsg}`);
          console.error('上传失败:', error);
          
          uni.showToast({
            title: error.message || '上传失败',
            icon: 'error',
            duration: 3000
          });
          
          resolve({
            success: false,
            error: error.message
          });
        }
      });

      // 监听上传进度
      uploadTask.onProgressUpdate((res) => {
        console.log('上传进度:', res.progress);
        // 可以在这里更新进度条
      });
    } catch (err) {
      uni.hideLoading();
      console.error('上传异常:', err);
      
      uni.showToast({
        title: err.message || '上传异常',
        icon: 'error',
        duration: 3000
      });
      
      resolve({
        success: false,
        error: err.message || '上传异常'
      });
    }
  });
};

/**
 * 批量上传图片到阿里云OSS
 * @param {Array<string>} filePaths - 文件路径数组
 * @param {Object} options - 可选配置
 * @returns {Promise<Object>} 上传结果
 */
export const uploadMultipleImagesToOss = async (filePaths, options = {}) => {
  try {
    if (!Array.isArray(filePaths) || filePaths.length === 0) {
      throw new Error('请选择要上传的文件');
    }

    uni.showLoading({
      title: '批量上传中...',
      mask: true
    });

    const results = [];
    const errors = [];

    for (let i = 0; i < filePaths.length; i++) {
      const filePath = filePaths[i];
      
      try {
        const result = await uploadImageToOss(filePath, {
          onProgress: (progress) => {
            // 计算总体进度
            const totalProgress = ((i + progress / 100) / filePaths.length) * 100;
            if (options.onProgress) {
              options.onProgress(totalProgress);
            }
          }
        });

        if (result.success) {
          results.push(result.data);
        } else {
          errors.push({
            file: filePath,
            error: result.error
          });
        }
      } catch (error) {
        errors.push({
          file: filePath,
          error: error.message
        });
      }
    }

    uni.hideLoading();

    const successCount = results.length;
    const errorCount = errors.length;

    if (errorCount > 0) {
      uni.showToast({
        title: `上传完成，成功${successCount}个，失败${errorCount}个`,
        icon: 'none',
        duration: 3000
      });
    } else {
      uni.showToast({
        title: '批量上传成功',
        icon: 'success',
        duration: 2000
      });
    }

    return {
      success: true,
      data: {
        success: results,
        errors: errors,
        total: filePaths.length,
        success_count: successCount,
        error_count: errorCount
      }
    };

  } catch (error) {
    uni.hideLoading();
    console.error('批量上传失败:', error);
    
    uni.showToast({
      title: error.message || '批量上传失败',
      icon: 'error',
      duration: 3000
    });
    
    return {
      success: false,
      error: error.message
    };
  }
};

/**
 * 删除阿里云OSS文件
 * @param {string} fileKey - 文件key
 * @returns {Promise<Object>} 删除结果
 */
export const deleteOssFile = async (fileKey) => {
  try {
    if (!fileKey) {
      throw new Error('文件key不能为空');
    }

    const result = await uni.request({
      url: `${BASE_URL}/upload/oss/delete`,
      method: 'POST',
      data: {
        key: fileKey
      },
      header: {
        'Content-Type': 'application/json'
      }
    });

    if (result.statusCode === 200 && result.data.code === 200) {
      uni.showToast({
        title: '删除成功',
        icon: 'success',
        duration: 2000
      });
      
      return {
        success: true,
        message: result.data.message
      };
    } else {
      throw new Error(result.data.message || '删除失败');
    }

  } catch (error) {
    console.error('删除文件失败:', error);
    
    uni.showToast({
      title: error.message || '删除失败',
      icon: 'error',
      duration: 3000
    });
    
    return {
      success: false,
      error: error.message
    };
  }
};

/**
 * 获取阿里云OSS文件信息
 * @param {string} fileKey - 文件key
 * @returns {Promise<Object>} 文件信息
 */
export const getOssFileInfo = async (fileKey) => {
  try {
    if (!fileKey) {
      throw new Error('文件key不能为空');
    }

    const result = await uni.request({
      url: `${BASE_URL}/upload/oss/file/info`,
      method: 'POST',
      data: {
        key: fileKey
      },
      header: {
        'Content-Type': 'application/json'
      }
    });

    if (result.statusCode === 200 && result.data.code === 200) {
      return {
        success: true,
        data: result.data.data
      };
    } else {
      throw new Error(result.data.message || '获取文件信息失败');
    }

  } catch (error) {
    console.error('获取文件信息失败:', error);
    
    return {
      success: false,
      error: error.message
    };
  }
};

/**
 * 检查阿里云OSS文件是否存在
 * @param {string} fileKey - 文件key
 * @returns {Promise<Object>} 检查结果
 */
export const checkOssFileExists = async (fileKey) => {
  try {
    if (!fileKey) {
      throw new Error('文件key不能为空');
    }

    const result = await uni.request({
      url: `${BASE_URL}/upload/oss/file/exists`,
      method: 'POST',
      data: {
        key: fileKey
      },
      header: {
        'Content-Type': 'application/json'
      }
    });

    if (result.statusCode === 200 && result.data.code === 200) {
      return {
        success: true,
        data: result.data.data
      };
    } else {
      throw new Error(result.data.message || '检查文件存在性失败');
    }

  } catch (error) {
    console.error('检查文件存在性失败:', error);
    
    return {
      success: false,
      error: error.message
    };
  }
};

/**
 * 批量删除阿里云OSS文件
 * @param {Array<string>} fileKeys - 文件key数组
 * @returns {Promise<Object>} 删除结果
 */
export const deleteMultipleOssFiles = async (fileKeys) => {
  try {
    if (!Array.isArray(fileKeys) || fileKeys.length === 0) {
      throw new Error('文件key列表不能为空');
    }

    const result = await uni.request({
      url: `${BASE_URL}/upload/oss/delete-multiple`,
      method: 'POST',
      data: {
        keys: fileKeys
      },
      header: {
        'Content-Type': 'application/json'
      }
    });

    if (result.statusCode === 200 && result.data.code === 200) {
      uni.showToast({
        title: '批量删除成功',
        icon: 'success',
        duration: 2000
      });
      
      return {
        success: true,
        data: result.data.data
      };
    } else {
      throw new Error(result.data.message || '批量删除失败');
    }

  } catch (error) {
    console.error('批量删除失败:', error);
    
    uni.showToast({
      title: error.message || '批量删除失败',
      icon: 'error',
      duration: 3000
    });
    
    return {
      success: false,
      error: error.message
    };
  }
};

/**
 * 选择图片并上传到OSS
 * @param {Object} options - 选择配置
 * @returns {Promise<Object>} 上传结果
 */
export const chooseAndUploadImage = async (options = {}) => {
  try {
    // 选择图片
    const chooseResult = await new Promise((resolve, reject) => {
      uni.chooseImage({
        count: options.count || 1,
        sizeType: options.sizeType || ['original', 'compressed'],
        sourceType: options.sourceType || ['album', 'camera'],
        success: resolve,
        fail: reject
      });
    });

    if (chooseResult.tempFilePaths.length === 0) {
      throw new Error('未选择图片');
    }

    // 上传图片
    if (chooseResult.tempFilePaths.length === 1) {
      // 单张图片上传
      return await uploadImageToOss(chooseResult.tempFilePaths[0], options);
    } else {
      // 多张图片上传
      return await uploadMultipleImagesToOss(chooseResult.tempFilePaths, options);
    }

  } catch (error) {
    console.error('选择并上传图片失败:', error);
    
    uni.showToast({
      title: error.message || '用户取消',
      icon: 'error',
      duration: 3000
    });
    
    return {
      success: false,
      error: error.message
    };
  }
}; 